package com.blog.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Service("jedisService")
public class JedisService implements InitializingBean {
	private static JedisPoolConfig config = new JedisPoolConfig(); 
	private static JedisPool jp;
	Jedis jedis;
	
	
	
	//kv操作
	public String add(String key,String value){
		String str = null;
		jedis=jp.getResource();
		try{
		str=jedis.set(key,value);}
		catch(Exception e){}
		finally{jp.returnResource(jedis);
		return str;}
	}
	
	public int inc(String key){
		int num = 0;
		jedis=jp.getResource();
		try{num=jedis.incr(key).intValue();}catch(Exception e){}finally{jp.returnResource(jedis);}
		return num; 
	}
	
	public Integer get(String key){
		int num = 0;
		jedis=jp.getResource();
		try{num=Integer.valueOf(jedis.get(key));}catch(Exception e){}finally{jp.returnResource(jedis);}
		return num;
	}

	/*数组操作*/
	public Integer lpush(String key,String value){
		int num = 0;
		jedis=jp.getResource();
		try{num=jedis.lpush(key,value).intValue();}catch(Exception e){}finally{jp.returnResource(jedis);}
		return num;
	}
	
	public List<String> lrange(String key){
		List<String> array = null ;
		jedis=jp.getResource();
		try{
			
			array=jedis.llen(key)>10?jedis.lrange(key,jedis.llen(key)-10,jedis.llen(key)):jedis.lrange(key,0,jedis.llen(key));
			
		
		}catch(Exception e){}finally{jp.returnResource(jedis);}
		return array;
	}
	
	public Set<String> keys(String keyPattern){
		Set<String> num = null;
		jedis=jp.getResource();
		try{num=jedis.keys(keyPattern);}catch(Exception e){}finally{jp.returnResource(jedis);}
		return num;
	}
	
	
	
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		//随时准备的线程数量 网站越大值越高
		//config.setMaxActive(30); 
		  config.setMaxIdle(10); 
		  config.setMaxWait(10); 
		  config.setTestOnBorrow(true); 
		  jp = new JedisPool(config, "127.0.0.1", 6379,3000000); 
	}
}
